package com.xique.park.service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.park.bean.domain.BaseUser;
import com.xique.park.mapper.BaseUserMapper;
import com.xique.park.service.service.IBaseUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户Service业务层处理
 *
 * @author caogq
 * @date 2021-12-14
 */
@Slf4j
@Service
public class BaseUserServiceImpl implements IBaseUserService {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private BaseUserMapper baseUserMapper;

    /**
     * 查询用户
     *
     * @param id 用户ID
     * @return 用户
     */
    @Override
    public BaseUser selectBaseUserById(Long id) {
        return baseUserMapper.selectById(id);
    }

    /**
     * 查询用户列表
     *
     * @param baseUser 用户
     * @return 用户
     */
    @Override
    public List<BaseUser> selectBaseUserList(BaseUser baseUser) {
        QueryWrapper<BaseUser> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(baseUser.getUserName()), "user_name", baseUser.getUserName());
        wrapper.eq(StringUtils.isNotEmpty(baseUser.getCellphone()), "cellphone", baseUser.getCellphone());
        wrapper.eq(StringUtils.isNotEmpty(baseUser.getAddress()), "address", baseUser.getAddress());
        wrapper.eq(StringUtils.isNotEmpty(baseUser.getGender()), "gender", baseUser.getGender());
        wrapper.eq(baseUser.getId() != null, "id", baseUser.getId());
        wrapper.orderByDesc("id");
        return baseUserMapper.selectList(wrapper);
    }

    /**
     * 新增用户
     *
     * @param baseUser 用户
     * @return 结果
     */
    @Override
    public int insertBaseUser(BaseUser baseUser) {
        baseUser.setCreateTime(DateUtils.getNowDate());
//        baseUser.setCreateUser(SecurityUtils.getUserId());
//        baseUser.setUpdateUser(SecurityUtils.getUserId());
        baseUser.setUpdateTime(DateUtils.getNowDate());
        return baseUserMapper.insert(baseUser);
    }

    /**
     * 修改用户
     *
     * @param baseUser 用户
     * @return 结果
     */
    @Override
    public int updateBaseUser(BaseUser baseUser) {
        baseUser.setUpdateTime(DateUtils.getNowDate());
        return baseUserMapper.updateById(baseUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteBaseUserByIds(List<Long> ids) {
        return baseUserMapper.deleteBatchIds(ids);
    }

    /**
     * 删除用户信息
     *
     * @param id 用户ID
     * @return 结果
     */
    @Override
    public int deleteBaseUserById(Long id) {
        return baseUserMapper.deleteById(id);
    }

    @Override
    public void batchAdd(List<BaseUser> userList) {
        long startTime = System.currentTimeMillis();
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        BaseUserMapper baseUserMapper = sqlSession.getMapper(BaseUserMapper.class);
        userList.forEach(baseUserMapper::insert);
        sqlSession.commit();
        sqlSession.clearCache();
        log.info("用户信息服务：批量新增耗时：{}秒", (System.currentTimeMillis() - startTime) / 1000);
    }

    @Override
    public List<BaseUser> selectBaseUserByPhone(String phone) {
        LambdaQueryWrapper<BaseUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BaseUser::getCellphone, phone);
        queryWrapper.eq(BaseUser::getDelFlag, UserConstants.DelFlag.NORMAL);
        //确保停车小程序登录通过手机号查询用户，存在多用户时，只查询最新创建的数据
        queryWrapper.orderByDesc(BaseUser::getId);
        log.error("[停车小程序]相同手机号存在多个用户，phone：{}",phone);
        return baseUserMapper.selectList(queryWrapper);
    }

    @Override
    public  List<BaseUser> selectBaseUserByParkMiniOpenId(String openId) {
        if (StrUtil.isEmpty(openId)) {
            return null;
        }
        LambdaQueryWrapper<BaseUser> condition = Wrappers.lambdaQuery();
        condition.eq(BaseUser::getParkWechatMiniOpenid, openId);
        condition.orderByDesc(BaseUser::getId);
        List<BaseUser> baseUsers = baseUserMapper.selectList(condition);
        if (baseUsers.size()>1){
            log.error("[停车小程序]相同openId存在多个用户，openid：{}",openId);
        }
        return baseUsers;
    }

    @Override
    public List<BaseUser> selectBaseUserByAlipayUserId(String alipayUserId) {
        if (StrUtil.isEmpty(alipayUserId)) {
            return null;
        }
        LambdaQueryWrapper<BaseUser> condition = Wrappers.lambdaQuery();
        condition.eq(BaseUser::getAlipayUserId, alipayUserId);
        List<BaseUser> baseUsers = baseUserMapper.selectList(condition);
        if (baseUsers.size()>1){
            log.error("[停车小程序]相同alipayUserId存在多个用户，alipayUserId：{}",alipayUserId);
        }
        return baseUsers;
    }

    @Override
    public List<BaseUser> selectBaseUserByParkMiniOpenIdAndPhone(String openId, String phone) {
        if (StrUtil.isEmpty(openId) || StrUtil.isEmpty(phone)) {
            return null;
        }
        LambdaQueryWrapper<BaseUser> condition = Wrappers.lambdaQuery();
        condition.eq(BaseUser::getParkWechatMiniOpenid, openId);
        condition.eq(BaseUser::getCellphone, phone);
        condition.orderByDesc(BaseUser::getId);
        List<BaseUser> baseUsers = baseUserMapper.selectList(condition);
        if (baseUsers.size()>1){
            log.error("[停车小程序]相同openId+手机号存在多个用户，open：{}，手机号：{}",openId,phone);
        }
        return baseUsers;
    }

    @Override
    public List<BaseUser> selectBaseUserByAliPayUserIdAndPhone(String aliPayUserId, String phone) {
        if (StrUtil.isEmpty(aliPayUserId) || StrUtil.isEmpty(phone)) {
            return null;
        }
        LambdaQueryWrapper<BaseUser> condition = Wrappers.lambdaQuery();
        condition.eq(BaseUser::getAlipayUserId, aliPayUserId);
        condition.eq(BaseUser::getCellphone, phone);
        condition.orderByDesc(BaseUser::getId);
        List<BaseUser> baseUsers = baseUserMapper.selectList(condition);
        if (baseUsers.size()>1){
            log.error("[停车小程序]相同alipayUserId+手机号存在多个用户，alipayUserId：{}，手机号：{}",aliPayUserId,phone);
        }
        return baseUsers;
    }
}
